package com.xoa.service.archive.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xoa.service.archive.FileUploadService;
import com.xoa.util.ToJson;
import com.xoa.util.archive.CommonUtils;
import com.xoa.util.archive.HttpUploadFile;
import org.apache.commons.io.FilenameUtils;
import org.springframework.stereotype.Service;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.ResourceBundle;

@Service
public class FileUploadServiceImpl implements FileUploadService {


    @Override
    public ToJson fileUploadFW(String value) throws Exception {
        JSONArray jsonArrayArchives=new JSONArray();
        ToJson toJson=new ToJson();
        try {
            //===1、获取文件共同地址
            ResourceBundle rb = ResourceBundle.getBundle("upload");
            String os = System.getProperty("os.name");
            StringBuffer sb = new StringBuffer();

            if (os.toLowerCase().startsWith("win")) {
                //sb=sb.append(rb.getString("upload.win"));
                //判断路径是否是相对路径，如果是的话，加上运行的路径
                String uploadPath = rb.getString("upload.win");
                if (uploadPath.indexOf(":") == -1) {
                    //获取运行时的路径
                    String basePath = this.getClass().getClassLoader().getResource(".").getPath() + File.pathSeparator;
                    //获取截取后的路径
                    String str2 = "";
                    if (basePath.indexOf("/xoa") != -1) {
                        //获取字符串的长度
                        int length = basePath.length();
                        //返回指定字符在此字符串中第一次出现处的索引
                        int index = basePath.indexOf("/xoa");
                        //从指定位置开始到指定位置结束截取字符串
                        str2 = basePath.substring(0, index);
                    }
                    sb = sb.append(str2 + "/xoa");
                }
                sb.append(uploadPath);

            } else {
                sb.append(rb.getString("upload.linux"));
            }
            //===2、获取文件地址集合
            String[] strings = value.split("\\*");
            JSONArray jsonArray=new JSONArray();
            List<File> listFiles=new ArrayList<>();

            //循环遍历附件信息拼接成jsonArry
            for (int i=0;i<strings.length;i++){
                JSONObject jsonObject1=new JSONObject();
                String[] fengGe=strings[i].split("&");

                for (int a=0;a<fengGe.length;a++){
                    String[] split = fengGe[a].split("=");
                    jsonObject1.put(split[0],split[1]);
                }
                jsonArray.add(jsonObject1);
            }
            for(Object object:jsonArray){
                JSONObject jsonObject1=(JSONObject)object;
                StringBuilder stringBuilder=new StringBuilder();
                stringBuilder.append(sb.toString()+File.separator+jsonObject1.getString("COMPANY")+File.separator+jsonObject1.getString("MODULE")
                        +File.separator+jsonObject1.getString("YM")+File.separator+jsonObject1.getString("ATTACHMENT_ID")+"."+jsonObject1.getString("ATTACHMENT_NAME"));
                listFiles.add(new File(stringBuilder.toString()));
            }
            //===3、上传文件
            for(File file:listFiles){
                JSONObject jsonObject1=new JSONObject();
                String uuidName = CommonUtils.getpfpID() + "." + FilenameUtils.getExtension(file.getName());
                //appid：由档案系统提供; path：为相对路径,其中/oaws：表文书目录，/oaht：表示合同目录,服务器会根据路径自动创建文件夹
                String year = new SimpleDateFormat("yyyy").format(new Date());
                String yearMothDaty = new SimpleDateFormat("yyyyMMdd").format(new Date());
               String flag= HttpUploadFile.fileUpload("http://106.13.80.96:8081/HttpUpload/uploadFile?appid=www&path=/oaws/"+year+"/"+yearMothDaty+"/" + uuidName, file);
                if(!flag.equals("success")){
                    throw new RuntimeException(flag);
                }

                //文件信息格式化json用与表单信息传递
                jsonObject1.put("name",file.getName().substring(0,file.getName().lastIndexOf(".")));
                jsonObject1.put("ext",file.getName().substring(file.getName().lastIndexOf(".")+1));
                jsonObject1.put("file","/"+year+"/"+yearMothDaty+"/"+uuidName);
                jsonArrayArchives.add(jsonObject1);
            }

            toJson.setFlag(0);
            toJson.setData(jsonArrayArchives);


        }catch (Exception e){
            System.out.println("档案接口文件上传失败");
            e.printStackTrace();
            toJson.setFlag(1);
            toJson.setMsg("档案接口文件上传失败:"+e.getMessage());
        }
        return toJson;
    }



    

    @Override
    public ToJson fileUploadHT(String value) throws Exception {
        JSONArray jsonArrayArchives=new JSONArray();
        ToJson toJson=new ToJson();
        try {
            //===1、获取文件共同地址
            ResourceBundle rb = ResourceBundle.getBundle("upload");
            String os = System.getProperty("os.name");
            StringBuffer sb = new StringBuffer();

            if (os.toLowerCase().startsWith("win")) {
                //sb=sb.append(rb.getString("upload.win"));
                //判断路径是否是相对路径，如果是的话，加上运行的路径
                String uploadPath = rb.getString("upload.win");
                if (uploadPath.indexOf(":") == -1) {
                    //获取运行时的路径
                    String basePath = this.getClass().getClassLoader().getResource(".").getPath() + File.pathSeparator;
                    //获取截取后的路径
                    String str2 = "";
                    if (basePath.indexOf("/xoa") != -1) {
                        //获取字符串的长度
                        int length = basePath.length();
                        //返回指定字符在此字符串中第一次出现处的索引
                        int index = basePath.indexOf("/xoa");
                        //从指定位置开始到指定位置结束截取字符串
                        str2 = basePath.substring(0, index);
                    }
                    sb = sb.append(str2 + "/xoa");
                }
                sb.append(uploadPath);

            } else {
                sb.append(rb.getString("upload.linux"));
            }
            //===2、获取文件地址集合
            String[] strings = value.split("\\*");
            JSONArray jsonArray=new JSONArray();
            List<File> listFiles=new ArrayList<>();

            //循环遍历附件信息拼接成jsonArry
            for (int i=0;i<strings.length;i++){
                JSONObject jsonObject1=new JSONObject();
                String[] fengGe=strings[i].split("&");

                for (int a=0;i<fengGe.length;i++){
                    String[] split = fengGe[a].split(":");
                    jsonObject1.put(split[0],split[1]);
                }
                jsonArray.add(jsonObject1);
            }
            //获取文件集合
            for(Object object:jsonArray){
                JSONObject jsonObject1=(JSONObject)object;
                StringBuilder stringBuilder=new StringBuilder();
                stringBuilder.append(sb.toString()+File.separator+jsonObject1.getString("COMPANY")+File.separator+jsonObject1.getString("MODULE")
                        +File.separator+jsonObject1.getString("YM")+File.separator+jsonObject1.getString("ATTACHMENT_ID")+"."+jsonObject1.getString("ATTACHMENT_NAME"));
                listFiles.add(new File(stringBuilder.toString()));
            }
            //===3、上传文件
            for(File file:listFiles){
                JSONObject jsonObject1=new JSONObject();
                String uuidName = CommonUtils.getpfpID() + "." + FilenameUtils.getExtension(file.getName());
                //appid：由档案系统提供; path：为相对路径,其中/oaws：表文书目录，/oaht：表示合同目录,服务器会根据路径自动创建文件夹
                String year = new SimpleDateFormat("yyyy").format(new Date());
                String yearMothDaty = new SimpleDateFormat("yyyyMMdd").format(new Date());
                String flag= HttpUploadFile.fileUpload("http://106.13.80.96:8081/HttpUpload/uploadFile?appid=www&path=/oaht/"+year+"/"+yearMothDaty+"/" + uuidName, file);
                if(!flag.equals("success")){
                    throw new RuntimeException(flag);
                }

                //文件信息格式化json用与表单信息传递
                jsonObject1.put("name",file.getName().substring(0,file.getName().lastIndexOf(".")));
                jsonObject1.put("ext",file.getName().substring(file.getName().lastIndexOf(".")+1));
                jsonObject1.put("file","/"+year+"/"+yearMothDaty+"/"+uuidName);
                jsonArrayArchives.add(jsonObject1);
            }

            toJson.setTurn(true);
            toJson.setData(jsonArrayArchives);

        }catch (Exception e){
            System.out.println("档案接口文件上传失败");
            e.printStackTrace();
            toJson.setTurn(false);
            toJson.setMsg("档案接口文件上传失败:"+e.getMessage());
        }
        return toJson;
    }
}
